import Viewer from "viewerjs";
import "viewerjs/dist/viewer.css";
import { defaultViewerOptions } from "@/config/viwerOption";

let viewerInstance = null;

export const ViewerDownloadClick =async (image) => {
  
  const url = image.src;
  const res = await fetch(url);
  const blob = await res.blob();
  const link = document.createElement("a");
  link.href = URL.createObjectURL(blob);
  link.download = url.split("/").pop().split("?")[0];
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(link.href);

}

export const ViewerApi = {
  /**
   * 打开图片查看器
   * @param {string|string[]} images 单图或多图数组
   * @param {object} options viewerjs 配置，可选
   */
  open(images, options = {}) {
    if (typeof images === "string") images = [images];

    // 创建隐藏容器
    const container = document.createElement("div");
    container.style.display = "none";
    console.log(images, container,'container');
    
    images.forEach((src, index) => {
      const img = document.createElement("img");
      img.src = src;
      img.alt = `image-${index}`;
      container.appendChild(img);
    });

    document.body.appendChild(container);

    // 销毁旧实例
    if (viewerInstance) {
      viewerInstance.destroy();
      viewerInstance = null;
    }

    // 创建新实例
    viewerInstance = new Viewer(container, {
      ...defaultViewerOptions,
      hidden() {
        viewerInstance.destroy();
        viewerInstance = null;
        document.body.removeChild(container);
      },
      toolbar: {
        ...defaultViewerOptions.toolbar,
        // 下载按钮
        // download: {
        //   show: 1,
        //   size: "large",
        //   click(...image) {
        //     ViewerDownloadClick(viewerInstance.image)
        //   },
        // },
      },
      ...options,
    });

    viewerInstance.show();
  },
};
